importScripts("./constant.js");


/**
 * @description: 消息监听
 * @return {*}
 */
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  const { type, tabId, url } = message;
  const {tab: {id: currentId}} = sender
  switch (type) {
    case "deploy":
      setPopupFn("../html/action_deploy.html").then(() => sendResponse(true));
      break;
    case "default":
      setPopupFn("../html/action_default.html", true).then(() => sendResponse(true));
      break;
    case "inspectSinglePage":
      setCurrentTab(Number(currentId), Number(tabId), url).then(res => sendResponse(res));
      break;
  }
  return true;
});


/**
 * @description: 设置popup
 * @param {*} popupPath  popup页面路径
 * @param {*} flag
 * @return {*}
 */
function setPopupFn(popupPath, flag) {
  return new Promise((resolve) => {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      let tabId = tabs.length ? tabs[0].id : null;
      let iconPath = '../asset/logo/icon_128x128.png'
      if(flag){
        iconPath = '../asset/logo/icon_default_128x128.png'
      }else{
        iconPath = '../asset/logo/icon_128x128.png'
      }
      chrome.action.setIcon({
        tabId: tabId,
        path: iconPath,
      });
      chrome.action
        .setPopup({
          tabId: tabId,
          popup: popupPath,
        })
        .then((res) => resolve(res));
    });
  });
}


/**
 * @description: 判断当前页是否为复制页面
 * @param {*} currentId  当前的tabid
 * @param {*} tabId  缓存的tabid
 * @param {*} url  插件可用的url
 * @return {*}
 */
function setCurrentTab(currentId, tabId, url){
  return new Promise(resolve => {
    chrome.tabs.query({}, tabs => {
        const tabRes = tabs.reduce((pre, cur) => {
          if(cur.url.includes(url)) pre.num++
          if(cur.id === tabId) pre.isTabFlag = true
          return pre
        }, {num: 0, isTabFlag: false})
        if(tabRes.num === 0){
          resolve(false)
        }else if(tabRes.num === 1){
          resolve(currentId)
        }else{
          if(!tabId){
            resolve(currentId)
          }else{
            if(tabRes.isTabFlag){
              if(currentId === tabId){
                resolve(currentId)
              }else{
                resolve(false)
              }
            }else{
              resolve(currentId)
            }
          }
        }
    })
  })
}


/**
 * @description: 初次进入页面识别，注意，在无痕模式下，监听不到
 * @return {*}
 */
chrome.history.onVisited.addListener(() => sendMessage({type: 'init_'}));


/**
 * @description: 往后页面脚本发送信息
 * @param {*} message
 * @return {*}
 */
function sendMessage(message){
  return new Promise((resolve, reject) => {
    const {tabId} = message
    if(tabId){
      chrome.tabs.sendMessage(tabId, message, res => resolve(res))
    }else{
      //Manifest中获取matches url
      const matchesUrl = chrome.runtime.getManifest()?.externally_connectable?.matches
      if (matchesUrl){
        chrome.tabs.query({
          url:matchesUrl,
          active: true,
          // currentWindow: false
        }, (tabs) => {
          if (tabs && tabs.length > 0){
              chrome.tabs.sendMessage(tabs[0]?.id, message, res => resolve(res))
          }
        })
      }
    }
  })
}
